package com.catsic.mod.specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.catsic.base.conditon.Condition;
import com.catsic.base.specification.BaseSpec;
import com.catsic.base.specification.QueryWraper;
import com.catsic.mod.condition.AnnouncesCondition;
import com.catsic.mod.entity.Announces;
/**
 * 
 * @author xiaobin
 * AnnouncesSpec
 */
public class AnnouncesSpec extends BaseSpec<Announces>{

	public AnnouncesSpec(Condition condition) {
		super(condition);
	}
    
	public Predicate toPredicate(Root<Announces> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
		AnnouncesCondition condition = (AnnouncesCondition) getCondition();
		Predicate p1=cb.equal(root.get("user").get("id"), condition.getCreateId());
		Predicate p2=cb.like(root.get("organId").as(String.class), "%"+condition.getOrganId()+"%" );
		Predicate p3=null;
		Predicate p4=null;
		if(StringUtils.isNotBlank(condition.getTitle())){
			p3=cb.like(root.get("title").as(String.class), "%"+condition.getTitle()+"%" );
		}
		if(StringUtils.isNotBlank(condition.getTypeName())){
			p4=cb.equal(root.get("drawer").get("id"), condition.getTypeName());
		}
		if(p3!=null && p4 !=null){
			query.where(cb.or(cb.and(p2,p3,p4),cb.and(p1,p3,p4)));
		}else if(p3!=null && p4 ==null){
        	query.where(cb.or(cb.and(p2,p3),cb.and(p1,p3)));
        }else if(p3==null && p4 !=null){
        	query.where(cb.or(cb.and(p2,p4),cb.and(p1,p4)));
        }else if(p3==null && p4 ==null){
        	query.where(cb.or(p1,p2));
        }
        query.orderBy(cb.desc(root.get("createTime")));  
        return query.getRestriction();
	}
	
	protected void addCondition(QueryWraper<Announces> queryWraper){
		
	}
}
